package com.qidian.service.impl;

import com.qidian.mapper.BankMapper;
import com.qidian.pojo.Bank;
import com.qidian.service.BankService;
import com.qidian.util.BankResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 戴着假发的程序员
 * @company 江苏极刻知学-起点编程
 */
@Service
@Transactional
public class BankServiceImpl implements BankService {

    @Autowired
    private BankMapper bankMapper;

    public BankResult save(Bank bank) {
        // 先做数据校验
        BankResult result = new BankResult();
        // 查重
        if(bankMapper.selectByName(bank.getBankName())!=null){
            result.setCode(501);
            result.setMsg("名称重复");
            return result;
        }
        // 补全数据
        bank.setStatus(1);
        if(bankMapper.insert(bank)==1){
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        return result;
    }

    @Override
    public Map queryByPage(String bankName, int page, int limit) {
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",bankMapper.queryCount(bankName));
        // 要通过页码和每页大小计算开始查询的位置
        map.put("data",bankMapper.queryByPage(bankName,(page-1)*limit,limit));
        return map;
    }

    public List<Bank> queryAll(){
        return bankMapper.selectAll();
    }

    @Override
    public Bank queryById(Integer bankId) {
        return bankMapper.selectById(bankId);
    }

    @Override
    public BankResult update(Bank bank) {
        BankResult result = new BankResult();
        result.setCode(500);
        // 编辑的时候，要检查名字是否重复
        // 根据新提交的题库的名字查询题库信息，如果查询出来的编号和当前要编辑的题库的编号不一致，则表示名称重复。否则就是可以编辑的。
        Bank bank1 = bankMapper.selectByName(bank.getBankName());
        if(bank1!=null && !bank1.getBankId().equals(bank.getBankId())){
            result.setCode(501);
            return result;
        }
        if(bankMapper.updateById(bank)==1){
            result.setCode(200);
        }
        return result;
    }

    @Override
    public BankResult delete(Integer bankId) {
        BankResult result = new BankResult();
        result.setCode(200);
        result.setData(bankMapper.deleteOne(bankId));
        return result;
    }

    @Override
    public BankResult delete(List<Integer> bankIds) {
        BankResult result = new BankResult();
        result.setCode(200);
        result.setData(bankMapper.delete(bankIds));
        return result;
    }

}
